package com.apes.scm.settle.payment.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.plugin.soe.store.database.repository.BusinessAttributeValueRepository;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.ledger.service.LedgerService;
import com.apes.scm.income.model.IncomeItem;
import com.apes.scm.income.repository.IncomeItemRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.settle.payment.model.*;
import com.apes.scm.settle.payment.repository.*;
import com.apes.scm.settle.settle.model.SettleSimple;
import com.apes.scm.settle.settle.model.TaxBillItem;
import com.apes.scm.settle.settle.respository.SettleSimpleRepository;
import com.apes.scm.settle.settle.respository.TaxBillItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 发票登记
 *
 * @author wuq
 * @create 2018-12-25 11:31
 */
@Service("paymentRegisterService")
public class PaymentRegisterService extends DomainService {

    @Autowired
    private PaymentRegisterRepository paymentRegisterRepository;

    @Autowired
    private TaxBillItemRepository taxBillItemRepository;

    @Autowired
    private LedgerService ledgerService;

    @Autowired
    private PaymentExecuteRecordRepository paymentExecuteRecordRepository;

    @Autowired
    private IncomeItemRepository incomeItemRepository;

    @Autowired
    private PaymentCostRepository paymentCostRepository;

    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private BusinessAttributeValueRepository businessAttributeValueRepository;

    @Autowired
    private SettleSimpleRepository settleSimpleRepository;


    public PaymentRegister create(SimpleRequest request) {
        PaymentRegister paymentRegister = request.getO(PaymentRegister.class);
        paymentRegister.setState("sent");
        paymentRegister.computeAmt();


        // 检查明细上是否金额为0
        checkItemAmount(paymentRegister);

        // 回写税票明细中的冻结金额
        if(!"disbursement".equals(paymentRegister.getOriginBusinessName()))
        writeBackTaxBillItems(paymentRegister);
        if (Objects.isNull(paymentRegister.getDept())) {
            //需求要客户结算相关界面去掉部门  但是对往来总账来说部门是必填的 所以在后台重新填充部门
            PartyRole company = paymentRegister.getCompany();
            Dept dept = SpringManager.getBean(DeptRepository.class).findAll(
                            JpaDsl.toCriteriaByEq("company", company, "deptType.id", "000007")).stream().findFirst()
                    .orElseThrow(() -> new RuntimeException(String.format("获取公司 [%s] 的销售部门失败", company.getId())));
            paymentRegister.setDept(dept);
        }

        //将费用明细的抵扣金额计入收入单的冻结金额
        if (paymentRegister.getType() != null && "supplier".equals(paymentRegister.getType())) {
            this.income(paymentRegister.getPaymentIncomeSet(), "create");
        } else {
            //客户收款登记模块中没有费用明细，所以需要清空
            Set<PaymentCost> paymentIncomeSet = paymentRegister.getPaymentIncomeSet();
            paymentIncomeSet.clear();
        }

        paymentRegister = paymentRegisterRepository.saveAndFlush(paymentRegister);
        // 写入总账 税票：将未清项转为冻结项（未清项减少，冻结项增加）
        transaction(paymentRegister, "invoice_unsettled", -1 * paymentRegister.getAmount(), "invoice_freeze", paymentRegister.getAmount());
        return paymentRegister;
    }

    public PaymentRegister createByPlatformSettle(SimpleRequest request) {
        PaymentRegister paymentRegister = request.getO(PaymentRegister.class);
        paymentRegister.setState("sent");
        paymentRegister.computeAmt();


        // 检查明细上是否金额为0
        checkItemAmount(paymentRegister);

        // 回写税票明细中的冻结金额
        if(!"disbursement".equals(paymentRegister.getOriginBusinessName()))
            writeBackTaxBillItems(paymentRegister);
        if (Objects.isNull(paymentRegister.getDept())) {
            //需求要客户结算相关界面去掉部门  但是对往来总账来说部门是必填的 所以在后台重新填充部门
            PartyRole company = paymentRegister.getCompany();
            Dept dept = SpringManager.getBean(DeptRepository.class).findAll(
                    JpaDsl.toCriteriaByEq("company", company, "deptType.id", "000007")).stream().findFirst()
                    .orElseThrow(() -> new RuntimeException(String.format("获取公司 [%s] 的销售部门失败", company.getId())));
            paymentRegister.setDept(dept);
        }

        paymentRegister = paymentRegisterRepository.saveAndFlush(paymentRegister);
        // 写入总账 税票：将未清项转为冻结项（未清项减少，冻结项增加）
        transaction(paymentRegister, "invoice_unsettled", -1 * paymentRegister.getAmount(), "invoice_freeze", paymentRegister.getAmount());
        return paymentRegister;
    }

    public PaymentRegister createByDisbursement(SimpleRequest request) {
        PaymentRegister paymentRegister = request.getO(PaymentRegister.class);
        paymentRegister.setState("sent");
        paymentRegister.computeAmt();
        // 检查明细上是否金额为0
        checkItemAmount(paymentRegister);

        // 回写税票明细中的冻结金额
        if(!"disbursement".equals(paymentRegister.getOriginBusinessName())) writeBackTaxBillItems(paymentRegister);
        if (Objects.isNull(paymentRegister.getDept())) {
            //需求要客户结算相关界面去掉部门  但是对往来总账来说部门是必填的 所以在后台重新填充部门
            PartyRole company = paymentRegister.getCompany();
            Dept dept = SpringManager.getBean(DeptRepository.class).findAll(
                            JpaDsl.toCriteriaByEq("company", company, "deptType.id", "000007")).stream().findFirst()
                    .orElseThrow(() -> new RuntimeException(String.format("获取公司 [%s] 的销售部门失败", company.getId())));
            paymentRegister.setDept(dept);
        }

        //将费用明细的抵扣金额计入收入单的冻结金额
        if (paymentRegister.getType() != null && "supplier".equals(paymentRegister.getType())) {
            this.income(paymentRegister.getPaymentIncomeSet(), "create");
        } else {
            //客户收款登记模块中没有费用明细，所以需要清空
            Set<PaymentCost> paymentIncomeSet = paymentRegister.getPaymentIncomeSet();
            paymentIncomeSet.clear();
        }
        paymentRegister = paymentRegisterRepository.saveAndFlush(paymentRegister);
        // 写入总账 税票：将未清项转为冻结项（未清项减少，冻结项增加）
        transaction(paymentRegister, "invoice_unsettled", 0.00, "invoice_freeze", 0.00);
        return paymentRegister;
    }

    public PaymentRegister approveByDisbursement(SimpleRequest request) {
        PaymentRegister data = (PaymentRegister) request.getData();
        PaymentRegister paymentRegister = paymentRegisterRepository.findOne(data.getId());
        paymentRegister.setState("approve");
        paymentRegister.setApproveUID(getPerson(request));
        paymentRegister.setApproveDate(new Date());

        //将费用明细的抵扣金额计入收入单的冻结金额
        if (paymentRegister.getType() != null && "supplier".equals(paymentRegister.getType())) {
            paymentRegister.setAmount(Double.parseDouble(request.get("paymentAmount").toString()));
            //将费用明细的抵扣金额计入收入单的冻结金额
            this.income(paymentRegister.getPaymentIncomeSet(), "approve");
        } else {
            //客户收款登记模块中没有费用明细，所以需要清空
            Set<PaymentCost> paymentIncomeSet = paymentRegister.getPaymentIncomeSet();
            paymentIncomeSet.clear();
        }
        // 写入收付款记录
        createPaymentExecuteRecord(paymentRegister);
        return paymentRegisterRepository.saveAndFlush(paymentRegister);
    }

    public PaymentRegister approve(SimpleRequest request) {
        String id = request.get("id");
        PaymentRegister paymentRegister = paymentRegisterRepository.findOne(id);
        paymentRegister.setState("approve");
        paymentRegister.setApproveUID(getPerson(request));
        paymentRegister.setApproveDate(new Date());

        //将费用明细的抵扣金额计入收入单的冻结金额
        if (paymentRegister.getType() != null && "supplier".equals(paymentRegister.getType())) {
            paymentRegister.setAmount(Double.parseDouble(request.get("paymentAmount").toString()));
            //将费用明细的抵扣金额计入收入单的冻结金额
            this.income(paymentRegister.getPaymentIncomeSet(), "approve");
        } else {
            //客户收款登记模块中没有费用明细，所以需要清空
            Set<PaymentCost> paymentIncomeSet = paymentRegister.getPaymentIncomeSet();
            paymentIncomeSet.clear();
        }
        // 写入收付款记录
        createPaymentExecuteRecord(paymentRegister);
        return paymentRegisterRepository.saveAndFlush(paymentRegister);
    }


    public void checkData(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        PaymentRegister oldPayment = paymentRegisterRepository.findOne(id);
        if (oldPayment == null) throw new RuntimeException("付款登记单【" + id + "】在系统中不存在。");
        if (oldPayment.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }

    /**
     * 检查明细项中的金额是否为0
     *
     * @param paymentRegister
     */
    private void checkItemAmount(PaymentRegister paymentRegister) {
        // 检查明细上是否金额为0
        paymentRegister.getPaymentRegisterItem().forEach(item -> {
            if (item.getAmount() == 0) {
                throw new RuntimeException("税票明细项" + item.getTaxBillItem().getId() + "金额存在为0项。");
            }
        });
    }

    /**
     * 更新采购付款单
     * 更新时：先将之前的冻结的数据还原，然后写入新的数据
     *
     * @param request
     * @return
     */
    public PaymentRegister update(SimpleRequest request) {
        checkData(request); // 检查数据

        PaymentRegister paymentRegister = request.getO(PaymentRegister.class);
        paymentRegister.computeAmt();
        checkItemAmount(paymentRegister);
        if (Objects.isNull(paymentRegister.getDept())) {
            //需求要客户结算相关界面去掉部门  但是对往来总账来说部门是必填的 所以在后台重新填充部门
            PartyRole company = paymentRegister.getCompany();
            Dept dept = SpringManager.getBean(DeptRepository.class).findAll(
                            JpaDsl.toCriteriaByEq("company", company, "deptType.id", "000007", "valid", true)).stream().findFirst()
                    .orElseThrow(() -> new RuntimeException(String.format("获取公司 [%s] 的销售部门失败", company.getId())));
            paymentRegister.setDept(dept);
        }
        /* 第一步：还原冻结的数据 **/
        PaymentRegister oldPaymentRegister = paymentRegisterRepository.findOne(paymentRegister.getId());
        reduceTaxBillItems(oldPaymentRegister);
        // 写入总账 税票：反向操作 将未清项转为冻结项（未清项增加，冻结项减少）
        transaction(paymentRegister, "invoice_unsettled", oldPaymentRegister.getAmount(), "invoice_freeze", -1 * oldPaymentRegister.getAmount());


        //todo 因为历史数据没有状态所以暂时使用PaymentIncomeSet判断
        if (StringUtils.isEmpty(request.get("sumPayableAmount"))) {
            paymentRegister.setType("customer");
        } else {
            paymentRegister.setType("supplier");
        }

        //将费用明细的抵扣金额计入收入单的冻结金额
        if (Objects.nonNull(paymentRegister.getType()) && "supplier".equals(paymentRegister.getType())) {
            PaymentRegister costs = paymentRegisterRepository.findOne(paymentRegister.getId());
            //还原冻结金额
            this.income(costs.getPaymentIncomeSet(), "delete");
            //重写冻结金额
            this.income(paymentRegister.getPaymentIncomeSet(), "create");
        } else {
            //客户收款登记模块中没有费用明细，所以需要清空
            paymentRegister.setPaymentIncomeSet(new HashSet<>());
        }

        /* 第二步：写入新的冻结数据 */
        writeBackTaxBillItems(paymentRegister);
        // 写入总账 税票：将未清项转为冻结项（未清项减少，冻结项增加）
        transaction(paymentRegister, "invoice_unsettled", -1 * paymentRegister.getAmount(), "invoice_freeze", paymentRegister.getAmount());
        return paymentRegisterRepository.saveAndFlush(paymentRegister);
    }

    /**
     * 回写供应商收入已扣款金额和冻结金额
     *
     * @param set   费用明细
     * @param state 状态
     * @return
     */
    public Set<PaymentCost> income(Set<PaymentCost> set, String state) {
        Set<PaymentCost> setPaymentCost = new HashSet<>();
        set.forEach(paymentCost -> {
            IncomeItem incomeItem = incomeItemRepository.findOne(paymentCost.getIncomeItemId().getId());
            switch (state) {
                case "create": {
                    incomeItem.setFreezeAmount(incomeItem.getFreezeAmount() + paymentCost.getAmount());
                    break;
                }
                case "approve": {
                    incomeItem.setRecoveryAmount(incomeItem.getRecoveryAmount() + paymentCost.getAmount());
                    incomeItem.setFreezeAmount(incomeItem.getFreezeAmount() - paymentCost.getAmount());
                    break;
                }
                case "delete": {
                    incomeItem.setFreezeAmount(incomeItem.getFreezeAmount() - paymentCost.getAmount());
                    paymentCostRepository.delete(paymentCost.getId());
                    break;
                }
                case "withdraw": {
                    incomeItem.setRecoveryAmount(incomeItem.getRecoveryAmount() - paymentCost.getAmount());
                    incomeItem.setFreezeAmount(incomeItem.getFreezeAmount() + paymentCost.getAmount());
                    break;
                }
            }
            incomeItemRepository.saveAndFlush(incomeItem);
            setPaymentCost.add(paymentCost);
        });
        return setPaymentCost;
    }


    public String delete(SimpleRequest request) {
        checkData(request); // 检查数据
        PaymentRegister paymentRegister = request.getO(PaymentRegister.class);

        // 还原冻结的数据
        PaymentRegister oldPaymentRegister = paymentRegisterRepository.findOne(paymentRegister.getId());
        reduceTaxBillItems(oldPaymentRegister);

        // 写入总账：反向操作 将未清项转为冻结项（未清项增加，冻结项减少）
        transaction(oldPaymentRegister, "invoice_unsettled", oldPaymentRegister.getAmount(), "invoice_freeze", -1 * oldPaymentRegister.getAmount());

        paymentRegister.setState("delete");
        paymentRegister.setDeleteDate(new Date());
        paymentRegister.setDeleteUID(getPerson(request));


        // 将费用明细的抵扣金额计入收入单的冻结金额
        if (paymentRegister.getType() != null && "supplier".equals(paymentRegister.getType())) {
            this.income(paymentRegister.getPaymentIncomeSet(), "delete");
        } else {
            //客户收款登记模块中没有费用明细，所以需要清空
            paymentRegister.setPaymentIncomeSet(new HashSet<>());
        }
        paymentRegisterRepository.saveAndFlush(paymentRegister);
        return "删除成功！";
    }

    /**
     * 审核撤回到创建
     *
     * @param request
     * @return
     */
    public PaymentRegister withdraw(SimpleRequest request) {
        PaymentRegister paymentRegister = request.getO(PaymentRegister.class);

        //撤回前删除已经创建好的收付款执行记录，否则可以不停的做重新做单
        List<PaymentExecuteRecord> oldPaymentExecuteRecord = paymentExecuteRecordRepository.findAll(
                JpaDsl.toCriteria("origin", "EQ", paymentRegister.getId(), "state", "EQ", "create"));
        oldPaymentExecuteRecord.forEach(paymentExecuteRecord -> paymentExecuteRecordRepository.delete(paymentExecuteRecord.getId()));

        //检查是否是审核或者已付款状态
        List states = Arrays.asList("approve", "done");
        List<PaymentExecuteRecord> paymentExecuteRecord = paymentExecuteRecordRepository.findAll(
                JpaDsl.toCriteria("origin", "EQ", paymentRegister.getId(), "state", "IN", states));
        if (paymentExecuteRecord.size() > 0) throw new RuntimeException("已创建付款单，禁止撤回");
        paymentRegister.setState("sent");

        //清空费用明细中的已抵扣金额
        this.income(paymentRegister.getPaymentIncomeSet(), "withdraw");
        return paymentRegisterRepository.saveAndFlush(paymentRegister);
    }


    /**
     * 审核时写入收付款记录
     *
     * @param paymentRegister 收付款登记
     */
    private void createPaymentExecuteRecord(PaymentRegister paymentRegister) {
        Map<String, Object> companyMap = new HashMap<>();
        companyMap.put("id", paymentRegister.getCompany().getId());

        Map<String, Object> deptMap = new HashMap<>();
        deptMap.put("id", paymentRegister.getDept() != null ? paymentRegister.getDept().getId() : null);

        Map<String, Object> partnerMap = new HashMap<>();
        partnerMap.put("id", paymentRegister.getPartner().getId());

        Map<String, Object> sceneMap = null;
        if (paymentRegister.getScene() != null) {
            sceneMap = MapUtil.mapper("id", paymentRegister.getScene().getId());
        }

        Map<String, Object> map = MapUtil.mapper("company", companyMap, "dept",
                paymentRegister.getDept() != null ? deptMap : null, "partner", partnerMap,
                "originBusinessType", paymentRegister.getInnerBusinessType(),
                "origin", paymentRegister.getId(), "accountBank", paymentRegister.getAccountBank(),
                "bank", paymentRegister.getBank(), "bankAccount", paymentRegister.getBankAccount(),
                "subbranch", paymentRegister.getSubbranch(), "amount", paymentRegister.getAmount(),
                "scene", sceneMap, "source", paymentRegister.getPaymentRegisterItem().stream()
                        .map(PaymentRegisterItem::getOrigin).filter(Objects::nonNull).collect(Collectors.joining(",")));
        this.invoke("paymentExecuteRecord.create", map);
    }



    /**
     * 审核时写入收付款记录
     *
     * @param paymentRegister 收付款登记
     */
    private void createPaymentExecute(PaymentRegister paymentRegister) {
        Map<String, Object> companyMap = new HashMap<>();
        companyMap.put("id", paymentRegister.getCompany().getId());

        Map<String, Object> deptMap = new HashMap<>();
        deptMap.put("id", paymentRegister.getDept() != null ? paymentRegister.getDept().getId() : null);

        Map<String, Object> partnerMap = new HashMap<>();
        partnerMap.put("id", paymentRegister.getPartner().getId());

        Map<String, Object> sceneMap = null;
        if (paymentRegister.getScene() != null) {
            sceneMap = MapUtil.mapper("id", paymentRegister.getScene().getId());
        }

        Map hashMap =new HashMap();
        paymentRegister.getPaymentRegisterItem().stream().forEach(v->{
            hashMap.put("source",v.getOrigin());
        });

        Map<String, Object> map = MapUtil.mapper("company", companyMap, "dept",
                paymentRegister.getDept() != null ? deptMap : null, "partner", partnerMap,
                "originBusinessType", paymentRegister.getInnerBusinessType(),
                "origin", paymentRegister.getId(), "accountBank", paymentRegister.getAccountBank(),
                "bank", paymentRegister.getBank(), "bankAccount", paymentRegister.getBankAccount(),
                "subbranch", paymentRegister.getSubbranch(), "amount", paymentRegister.getAmount(),
                "scene", sceneMap, "source", hashMap.get("source"));
        this.invoke("paymentExecuteRecord.create", map);
    }

    /**
     * 回写税票明细中的冻结金额
     *
     * @param paymentRegister 付款登记信息
     */
    private void writeBackTaxBillItems(PaymentRegister paymentRegister) {
        paymentRegister.getPaymentRegisterItem().forEach(item -> {
            TaxBillItem taxBillItem = item.getTaxBillItem();
            taxBillItem.changeFreezeAmount(item.getAmount());
            taxBillItemRepository.saveAndFlush(taxBillItem);
        });
    }

    @Listener(topic = "event:payment.pay")
    public boolean pay(SimpleRequest request) {
        JSONObject json = request.getJO();
        if (!json.getString("originBusinessType").equals(PaymentRegister.class.getSimpleName())) return false;

        PaymentRegister paymentRegister = paymentRegisterRepository.findOne(json.getString("origin"));

        // 还原冻结的数据,将冻结数转为付款数
        if (!"disbursement".equals(paymentRegister.getOriginBusinessName()))
            paymentRegister.getPaymentRegisterItem().forEach(item -> {
                TaxBillItem taxBillItem = item.getTaxBillItem();
                if (Objects.isNull(taxBillItem)) return;
                taxBillItem.changeFreezeAmount(-1 * item.getAmount());
                taxBillItem.changeActualAmount(item.getAmount());
                taxBillItemRepository.saveAndFlush(taxBillItem);
            });

        // 税票和账款记录
        transaction(paymentRegister, "invoice_freeze", -1 * paymentRegister.getAmount(), "invoice_settled", paymentRegister.getAmount());
        transaction(paymentRegister, "current_invoiced", -1 * paymentRegister.getAmount(), "current_settled", paymentRegister.getAmount());

        // 收款类型的写入占款
        if ("Customer".equals(paymentRegister.getPartner().getRole().getId())) {
            transaction(paymentRegister, "occupy_unsettled", -1 * paymentRegister.getAmount(), "occupy_settled", paymentRegister.getAmount());
        }
        paymentRegister.setState("executive");
        paymentRegisterRepository.saveAndFlush(paymentRegister);
        return true;
    }

    /**
     * 还原税票明细中的冻结金额
     *
     * @param oldPaymentRegister 原始付款单信息
     */
    private void reduceTaxBillItems(PaymentRegister oldPaymentRegister) {
        oldPaymentRegister.getPaymentRegisterItem().forEach(item -> {
            TaxBillItem taxBillItem = item.getTaxBillItem();
            taxBillItem.changeFreezeAmount(-1 * item.getAmount());
            taxBillItemRepository.saveAndFlush(taxBillItem);
        });
    }

    /**
     * 写入总账
     *
     * @param paymentRegister 付款单信息
     * @param items           可变参数明细
     */
    private void transaction(PaymentRegister paymentRegister, Object... items) {
        ledgerService.transaction(paymentRegister.getCompany(), paymentRegister.getDept(), paymentRegister.getPartner(),
                paymentRegister.getCooperation().getInventoryMode(), paymentRegister.getCooperation().getAccountingMethod(),
                paymentRegister.getInnerBusinessKey(), paymentRegister.getInnerBusinessType(), new Date(), items);
    }

    @Autowired
    private PaymentService paymentService;


    public void createSettleSimple(PaymentRegister paymentRegister) {
        paymentRegister.setState("sent");
        paymentRegister.computeAmt();

        // 检查明细上是否金额为0
        checkItemAmount(paymentRegister);

        // 回写税票明细中的冻结金额
        if (!"disbursement".equals(paymentRegister.getOriginBusinessName()))
            writeBackTaxBillItems(paymentRegister);
        if (Objects.isNull(paymentRegister.getDept())) {
            //需求要客户结算相关界面去掉部门  但是对往来总账来说部门是必填的 所以在后台重新填充部门
            PartyRole company = paymentRegister.getCompany();
            Dept dept = SpringManager.getBean(DeptRepository.class).findAll(
                            JpaDsl.toCriteriaByEq("company", company, "deptType.id", "000007")).stream().findFirst()
                    .orElseThrow(() -> new RuntimeException(String.format("获取公司 [%s] 的销售部门失败", company.getId())));
            paymentRegister.setDept(dept);
        }

         approveSettleSimple(paymentRegisterRepository.saveAndFlush(paymentRegister));//创建付款登记
    }


    public void approveSettleSimple(PaymentRegister paymentRegister) {
        paymentRegister.setState("approve");
        paymentRegister.setApproveUID(partyRoleRepository.findOne(paymentRegister.getCreator()));
        paymentRegister.setApproveDate(new Date());

        createPaymentExecute(paymentRegister);// 写入收付款记录

        paymentRegisterRepository.saveAndFlush(paymentRegister);//审核付款登记

        paymentService.createSettleSimple(getPayment(paymentRegister));//自动生成付款单
    }

    private Payment getPayment(PaymentRegister paymentRegister) {
        Payment payment = new Payment();
        payment.setPartner(paymentRegister.getPartner());
        payment.setCompany(paymentRegister.getCompany());
        payment.setCreator(paymentRegister.getCreator());
        payment.setPaymentType(businessAttributeValueRepository.getOne("Payment.paymentType.invoice_payment"));
        payment.setCreateDate(new Date());
        Set<PaymentItem> paymentItemSet = new HashSet<>();
        paymentRegister.getPaymentRegisterItem().forEach(v -> {
            PaymentItem paymentItem=new PaymentItem();
            paymentItem.setOriginBusinessType("PaymentRegister");
            paymentItem.setOrigin(paymentRegister.getId());
            paymentItem.setSource(v.getOrigin());
            paymentItem.setAmount(v.getAmount());
            payment.setSource(v.getOrigin());
            paymentItem.setPaymentExecuteRecord(paymentExecuteRecordRepository.findAll(JpaDsl.toCriteriaByEq("source",v.getOrigin())).get(0));
            paymentItemSet.add(paymentItem);
        });
        payment.setPaymentItemSet(paymentItemSet);
        return payment;
    }


}
